const Router = require('koa-router');
const router = new Router();
const multer = require('@koa/multer');
const files = require('../models/files');
const path = require('path');
const fs = require('fs').promises;

router.prefix('/files');

// 配置 multer
const storage = multer.diskStorage({
    destination: async function (req, file, cb) {
        try {
            // 创建临时上传目录
            const tempDir = path.join(__dirname, '../temp');
            await fs.mkdir(tempDir, { recursive: true });
            cb(null, tempDir);
        } catch (error) {
            cb(error);
        }
    },
    filename: function (req, file, cb) {
        // 使用时间戳和原始文件名，避免文件名冲突
        const timestamp = Date.now();
        const ext = path.extname(file.originalname);
        const basename = path.basename(file.originalname, ext);
        cb(null, `${basename}-${timestamp}${ext}`);
    }
});

const upload = multer({ 
    storage: storage,
    limits: {
        fileSize: 200 * 1024 * 1024 // 200MB
    }
});

// 列出文件
router.get('/list', async (ctx) => {
    try {
        const currentPath = ctx.query.path || '';
        const result = await files.listFiles(currentPath);
        ctx.body = result;
    } catch (error) {
        console.error('List files error:', error);
        ctx.status = 500;
        ctx.body = {
            status: 0,
            message: '获取文件列表失败: ' + error.message
        };
    }
});

// 上传文件
router.post('/upload', upload.single('file'), async (ctx) => {
    try {
        if (!ctx.file) {
            ctx.status = 400;
            ctx.body = {
                status: 0,
                message: '没有文件被上传'
            };
            return;
        }

        // 获取目标路径
        const targetPath = ctx.request.body.path;
        if (!targetPath) {
            ctx.status = 400;
            ctx.body = {
                status: 0,
                message: '缺少目标路径'
            };
            return;
        }

        // 验证路径
        if (!files.validatePath(targetPath)) {
            ctx.status = 400;
            ctx.body = {
                status: 0,
                message: '无效的目标路径'
            };
            return;
        }

        // 确保目标目录存在
        const targetDir = path.dirname(targetPath);
        await fs.mkdir(targetDir, { recursive: true });

        // 移动文件到最终位置
        await fs.rename(ctx.file.path, targetPath);

        ctx.body = {
            status: 1,
            message: '文件上传成功',
            data: {
                path: targetPath.replace(/\\/g, '/'),
                name: path.basename(targetPath)
            }
        };
    } catch (error) {
        console.error('Upload error:', error);
        // 如果上传失败，清理临时文件
        if (ctx.file && ctx.file.path) {
            try {
                await fs.unlink(ctx.file.path);
            } catch (unlinkError) {
                console.error('Failed to clean up temp file:', unlinkError);
            }
        }
        ctx.status = 500;
        ctx.body = {
            status: 0,
            message: '上传失败: ' + error.message
        };
    }
});

router.get('/download', async (ctx) => {
  try {
      const filepath = ctx.query.filepath;
      console.log('Requested file path:', filepath); // 调试用

      if (!filepath) {
          ctx.status = 400;
          ctx.body = {
              status: 0,
              message: '未指定文件路径'
          };
          return;
      }

      const result = await files.downloadFile(filepath);
      
      if (result.status === 1) {
          ctx.attachment(result.data.filename);
          ctx.type = 'application/octet-stream';
          ctx.body = result.data.stream;
      } else {
          ctx.status = 404;
          ctx.body = result;
      }
  } catch (error) {
      console.error('Download error:', error);
      ctx.status = 500;
      ctx.body = {
          status: 0,
          message: '下载失败: ' + error.message
      };
  }
});

// 删除文件或目录
router.delete('/delete', async (ctx) => {
    try {
        const { path: targetPath, isDirectory } = ctx.request.body;
        
        if (!targetPath) {
            ctx.status = 400;
            ctx.body = {
                status: 0,
                message: '路径不能为空'
            };
            return;
        }

        // 验证路径
        if (!files.validatePath(targetPath)) {
            ctx.status = 400;
            ctx.body = {
                status: 0,
                message: '无效的路径'
            };
            return;
        }

        ctx.body = await files.deleteItem(targetPath, isDirectory);
    } catch (error) {
        console.error('Delete error:', error);
        ctx.status = 500;
        ctx.body = {
            status: 0,
            message: '删除失败: ' + error.message
        };
    }
});

// 重命名文件或目录
router.put('/rename', async (ctx) => {
    try {
        const { oldPath, newPath } = ctx.request.body;
        
        if (!oldPath || !newPath) {
            ctx.status = 400;
            ctx.body = {
                status: 0,
                message: '路径不能为空'
            };
            return;
        }

        // 验证路径
        if (!files.validatePath(oldPath) || !files.validatePath(newPath)) {
            ctx.status = 400;
            ctx.body = {
                status: 0,
                message: '无效的路径'
            };
            return;
        }

        ctx.body = await files.renameItem(oldPath, newPath);
    } catch (error) {
        console.error('Rename error:', error);
        ctx.status = 500;
        ctx.body = {
            status: 0,
            message: '重命名失败: ' + error.message
        };
    }
});

// 创建目录
router.post('/mkdir', async (ctx) => {
    try {
        const { path: dirPath } = ctx.request.body;
        
        if (!dirPath) {
            ctx.status = 400;
            ctx.body = {
                status: 0,
                message: '路径不能为空'
            };
            return;
        }

        // 验证路径
        if (!files.validatePath(dirPath)) {
            ctx.status = 400;
            ctx.body = {
                status: 0,
                message: '无效的路径'
            };
            return;
        }

        ctx.body = await files.createDir(dirPath);
    } catch (error) {
        console.error('Create directory error:', error);
        ctx.status = 500;
        ctx.body = {
            status: 0,
            message: '创建目录失败: ' + error.message
        };
    }
});

module.exports = router;